package main

import (
	"fmt"
	"github.com/go-redis/redis/v8"
)

// redis

var redisdb *redis.Client

func initRedis() (err error) {
	redisdb = redis.NewClient(&redis.Options{
		Addr:     "10.10.10.101:6379",
		Password: "",
		DB:       0,
	})
	_, err = redisdb.Ping(redisdb.Context()).Result()
	return
}
func main() {
	err := initRedis()
	if err != nil {
		fmt.Printf("connect redis failed, err: %v\n", err)
		return
	}
	fmt.Println("连接成功")

	// zset
	key := "lalala"
	items := []*redis.Z{
		&redis.Z{Score: 100, Member: "Golang"},
		&redis.Z{Score: 70, Member: "Python"},
		&redis.Z{Score: 90, Member: "Java"},
	}
	// 把元素追加到key, 执行完去数据库查看
	redisdb.ZAdd(redisdb.Context(), key, items...)

	// 给Golang加20分
	result, err := redisdb.ZIncrBy(redisdb.Context(), key, 20, "Golang").Result()
	if err != nil {
		fmt.Printf("zincrby failed, err: %v\n", err)
		return
	}
	fmt.Println(result) // 120

	// 取95~100分的
	op := &redis.ZRangeBy{
		Min: "70",
		Max: "120",
	}
	ret, err := redisdb.ZRangeByScoreWithScores(redisdb.Context(), key, op).Result()
	if err != nil {
		fmt.Printf("zrangebyscore failed, err:%v\n", err)
		return
	}
	for _, z := range ret {
		fmt.Println(z.Member, z.Score)
	}
}
